import 'dart:async';
import 'dart:ui';

import 'package:flustars/flustars.dart';
import 'package:get/get.dart';

class WhiteboardController extends GetxController with StateMixin<PointsModel> {
  final _points = List<PointsModel>().obs;
  get points => _points;
  int _playTime = 0;
  void onInit() {
    print("WhiteboardController onInit");
    super.onInit();
    // show loading on start, data on success
    // and error message on error with 0 boilerplate
    Future.delayed(Duration(seconds: 2)).then((data) {
      change(PointsModel(), status: RxStatus.success());
    }, onError: (err) {
      change(null, status: RxStatus.error(err.toString()));
    });
  }

  init() {
    Timer.periodic(Duration(milliseconds: 1), (timer) {
      _playTime += 1;
    });
  }

  add(Offset offset) {
    _points.add(PointsModel(offset: offset, t: DateUtil.getNowDateMs()));
  }

  replay() {
    final rxList = List<PointsModel>().obs..addAll(_points);
    _points.clear();
    int i = 0;
    Future.delayed(Duration(seconds: 2), () {
      play() {
        if (i < rxList.length - 1) {
          _points.add(rxList[i]);
          Future.delayed(Duration(milliseconds: rxList[i + 1].t - rxList[i].t), () => play());
          i++;
        } else {
          return;
        }
      }

      play();
    });
  }
}

class PointsModel {
  Offset offset;
  int t;

  PointsModel({this.offset, this.t});

  PointsModel.fromJson(Map<String, dynamic> json) {
    this.offset = json['offset'];
    this.t = json['t'];
  }

  Map<String, dynamic> toJson() => {'offset': offset, 't': t};
}
